package main

import "fmt"

// 切片：即动态数组
func main() {
	var numbers = make([]int, 3, 5)
	printSlice(numbers)

	//空（nil）切片
	println("===============")
	var numbers2 []int
	printSlice(numbers2)
	if numbers2 == nil {
		println("切片是空的...")
	}

	//切片截取
	println("===============")
	//创建切片
	numbers3 := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
	printSlice(numbers3)
	//打印原始切片
	fmt.Println("numbers3 ==", numbers3)
	//打印子切片从索引1（包含）到索引4（不包含）
	fmt.Println("numbers3[1:4] ==", numbers3[1:4])
	//默认下限为0
	fmt.Println("numbers[:3] ==", numbers3[:3])
	//默认上限为len(s)
	fmt.Println("numbers3[4:] ==", numbers3[4:])

	//切片扩容
	println("========切片扩容=======")
	sliceDemo()
}

func printSlice(x []int) {
	fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x)
}

func sliceDemo() {
	var numbers []int
	printSlice(numbers)

	//允许追加空切片
	numbers = append(numbers, 0)
	printSlice(numbers)

	//向切片添加一个元素
	numbers = append(numbers, 1)
	printSlice(numbers)

	//同时添加多个元素
	numbers = append(numbers, 2, 3, 4)
	printSlice(numbers)

	//创建切片numbers1是之前切片的两倍容量
	numbers1 := make([]int, len(numbers), (cap(numbers))*2)

	//拷贝numbers的内容到numbers1
	copy(numbers1, numbers)
	printSlice(numbers1)
}
